
import com.acarter.scenemonitor.SceneMonitor;
import java.util.logging.Logger;

import com.jme.app.SimpleGame;
import com.jme.math.Vector3f;
import com.jme.scene.Spatial;
import com.jme.system.DisplaySystem;
import com.jmex.model.ogredotscene.DotSceneHandler;
import com.jmex.model.ogrexml.anim.MeshAnimationController;
import com.sceneworker.SceneWorker;
import java.io.File;
import java.util.Date;

/**
 *
 * @author czarnik_a
 */
public class Main extends SimpleGame {

    private static final Logger logger = Logger.getLogger(
            Main.class.getName());
    private MeshAnimationController controller = null;
    private String[] animationNames = null;
    private long switchTime = -1L;
    // We will switch to next animation when this time is reached
    private long cycleMillis = 3000L;
    private int animationIndex = -1;
    private DotSceneHandler dotSceneLoader;

    public static void main(String[] args) {
        Main app = new Main();
        app.setConfigShowMode(ConfigShowMode.AlwaysShow);
        app.start();
    }

    @Override
    protected void simpleInitGame() {
        DisplaySystem.getDisplaySystem().setTitle("MainTest");
        cam.setLocation(new Vector3f(0f, 1f, 3f));

        // Move the camera in closer
        dotSceneLoader = new DotSceneHandler();
        File testsceneFile = new File("src/jmetest/data/Testscene.xml");
        dotSceneLoader.loadScene(testsceneFile);
        rootNode.attachChild(dotSceneLoader.getJmeSceneNode());

        if (rootNode.getChild("Ninja") != null) {
            Spatial ninjaNode = rootNode.getChild("Ninja");
            // N.b. Spatial.getChild(String) returns a descendant, not necessarily
            // a child.
            if (ninjaNode == null) {
                throw new RuntimeException("The 'Ninja' is missing");
            }
            controller = (MeshAnimationController) ninjaNode.getController(0);
            if (controller == null) {
                throw new RuntimeException("'Ninja' is missing his Controller");
            }
            animationNames = controller.getAnimationNames().toArray(new String[0]);
            logger.info(Integer.toString(animationNames.length)
                    + " animations loaded");
        }
        SceneWorker.inst().initialiseSceneWorkerAndMonitor();
        SceneMonitor.getMonitor().registerNode(rootNode, "root");

    }

    @Override
    public void simpleUpdate() {
        super.simpleUpdate();
        if (dotSceneLoader.getJmeSkybox() != null)
        {
                dotSceneLoader.getJmeSkybox().setLocalTranslation(cam.getLocation());
        }
        
        long now = new Date().getTime();
        if (switchTime > now) {
            return;
        }
        if (++animationIndex == animationNames.length) {
            animationIndex = 0;
        }
        controller.setAnimation(animationNames[animationIndex]);
        switchTime = now + cycleMillis;
        SceneMonitor.getMonitor().updateViewer(tpf);
    }
}
